package cn.mesmile.flink.monitor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zb
 * @date 2021/8/29 22:56
 * @Description
 */
public class FlinkMonitorCEPApiAPP {

    /**
     * 每30秒统计，过去1分钟，各个接口的各个状态码次数，1分钟内超过5次则告警
     * CEP 乱序延迟问题
     *
     * Flink CEP会将事件进行缓存，在相应的watermark到底之后，Flink CEP将缓存中的事件按照事件时间进行升序排序，然后再进行的模式匹配。
     * 当watermark到达时，处理该缓冲区中事件时间小于watermark时间的所有数据。
     * 时间小于上次的watermark的时间就是迟到的数据，迟到的数据需要用侧输出流处理
     */
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
        environment.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
        environment.setParallelism(1);

        //java,2022-11-11 09-10-10,15
        DataStream<AccessLogDO> ds =  environment.addSource(new AccessLogSource());
        // 过滤
        SingleOutputStreamOperator<AccessLogDO> filterDS = ds.filter(new FilterFunction<AccessLogDO>() {
            @Override
            public boolean filter(AccessLogDO value) throws Exception {
                return StrUtil.isNotBlank(value.getUrl());
            }
        });
        //指定watermark
        SingleOutputStreamOperator<AccessLogDO> watermarkDS = filterDS.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        //指定允许乱序延迟的最大时间 3
                        .<AccessLogDO>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        //指定POJO事件时间列，毫秒
                        .withTimestampAssigner(
                                (event, timestamp) -> event.getCreateTime().getTime()
                        )
        );
        //最后的兜底数据
        OutputTag<AccessLogDO> lateData = new OutputTag<AccessLogDO>("lateDataLog"){};

        //多个字段分组
        KeyedStream<AccessLogDO, Tuple2<String, Integer>> keyedStream = watermarkDS.keyBy(
                new KeySelector<AccessLogDO, Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> getKey(AccessLogDO value) throws Exception {
                        return Tuple2.of(value.getUrl(),value.getHttpCode());
                    }
                });

        Pattern<AccessLogDO, AccessLogDO> errorCode = Pattern.<AccessLogDO>begin("errorCode").where(new SimpleCondition<AccessLogDO>() {
            @Override
            public boolean filter(AccessLogDO value) throws Exception {
                return value.getHttpCode() != 200;
            }
        }).timesOrMore(3).within(Time.seconds(60));
        // 匹配数据流
        PatternStream<AccessLogDO> pattern = CEP.pattern(keyedStream, errorCode);
        // 获取结果
        SingleOutputStreamOperator<ResultCount> cepResult = pattern.select(new PatternSelectFunction<AccessLogDO, ResultCount>() {
            @Override
            public ResultCount select(Map<String, List<AccessLogDO>> map) throws Exception {
                List<AccessLogDO> list = map.get("errorCode");
                AccessLogDO accessLogDO = list.get(0);

                ResultCount resultCount = new ResultCount();
                resultCount.setUrl(accessLogDO.getUrl());
                resultCount.setCount(Long.valueOf(list.size()));
                resultCount.setCode(accessLogDO.getHttpCode());

                return resultCount;
            }
        });

        cepResult.print("接口警告：");

        environment.execute("monitor cep job");
    }
}
